package com.udaos.modules.student.controllers;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.adaptor.WhaleAdaptor;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import com.udaos.common.base.Result;
import com.udaos.common.filter.PrivateFilter;
import com.udaos.common.page.DataTableColumn;
import com.udaos.common.page.DataTableOrder;
import com.udaos.models.call.Ud_call;
import com.udaos.models.school.Ud_school;
import com.udaos.models.student.Ud_student;
import com.udaos.models.student.Ud_student_attachment;
import com.udaos.models.student.Ud_student_record;
import com.udaos.models.student.Ud_student_score;
import com.udaos.models.sys.Sys_user;
import com.udaos.modules.company.services.UdCompanyService;
import com.udaos.modules.field.utils.ImageUtils;
import com.udaos.modules.school.services.UdSchoolService;
import com.udaos.modules.student.services.UdStudentAttachmentService;
import com.udaos.modules.student.services.UdStudentRecordService;
import com.udaos.modules.student.services.UdStudentScoreService;
import com.udaos.modules.student.services.UdStudentService;
/**
 * 学员管理
 * @author mutaotao
 *
 */
@IocBean
@At("/platform/student")
@Filters({ @By(type = PrivateFilter.class)})
public class UdStudentController {

	
	@Inject
	private UdCompanyService companyService;
	@Inject
	private UdStudentService studentService;
	@Inject
	private UdSchoolService schoolService;
	@Inject
	private UdStudentAttachmentService attachmentService;
	@Inject
	private UdStudentScoreService scoreService;
	@Inject
	private UdStudentRecordService studentRecordService;
	


	/**
	 * 首页
	 */
	@At("")
	@Ok("beetl:/platform/student/index.html")
	@RequiresAuthentication
	public void index() {

	}
	/**
	 * 加载数据
	 * @param name
	 * @param length
	 * @param start
	 * @param draw
	 * @param order
	 * @param columns
	 * @return
	 */
	@At
	@Ok("json:full")
	@RequiresAuthentication
	public Object data(@Param("name") String name,@Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns) {
		Cnd cnd = Cnd.NEW();
		if (!Strings.isBlank(name))
			cnd.and("name", "like", "%" + name + "%");
		return studentService.data(length, start, draw, order, columns, cnd, null);
	}

	/**
	 * 修改
	 * @param id
	 * @return
	 */
	@At("/edit/?")
	@Ok("beetl:/platform/student/edit.html")
	@RequiresAuthentication
	public Object edit(String id) {
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("student", studentService.fetch(id));
		//档案归属主体
		map.put("company",companyService.fetch(studentService.fetch(id).getCompany_id()));
		//获取入学进度
		map.put("enroll_progress",studentService.getEnrollProgress());
		//培训进度
		map.put("train_progress",studentService.getTrainProgress());
		//驾校
		map.put("schoolList",schoolService.find());
		//场地
		map.put("fieldList", studentService.getFieldList());
		//教练
		map.put("coachList", studentService.getCoachList());
		return map;
	}
	
	/**
	 * do修改
	 * @param ud_coach
	 * @param req
	 * @return
	 */
	@At
	@Ok("json")
	@RequiresAuthentication
	@AdaptBy(type = WhaleAdaptor.class)
	public Object editDo(@Param("..") Ud_student student,@Param("enroll_timeStr") String enroll_timeStr,@Param("subject1_pass_timeStr") String subject1_pass_timeStr
			,@Param("subject2_start_timeStr") String subject2_start_timeStr,@Param("subject2_pass_timeStr") String subject2_pass_timeStr
			,@Param("subject3_start_timeStr") String subject3_start_timeStr,@Param("subject3_pass_timeStr") String subject3_pass_timeStr
			,@Param("subject4_pass_timeStr") String subject4_pass_timeStr) {
		try {
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			 if(!Strings.isBlank(enroll_timeStr)){
				 student.setEnroll_time((int) (sdf.parse(enroll_timeStr).getTime() / 1000));
			 }
			 if(!Strings.isBlank(subject1_pass_timeStr)){
				 student.setSubject1_pass_time((int) (sdf.parse(subject1_pass_timeStr).getTime() / 1000));
			 }
			 if(!Strings.isBlank(subject2_start_timeStr)){
				 student.setSubject2_start_time((int) (sdf.parse(subject2_start_timeStr).getTime() / 1000));
			 }
			 if(!Strings.isBlank(subject2_pass_timeStr)){
				 student.setSubject2_pass_time((int) (sdf.parse(subject2_pass_timeStr).getTime() / 1000));
			 }
			 if(!Strings.isBlank(subject3_start_timeStr)){
				 student.setSubject3_start_time((int) (sdf.parse(subject3_start_timeStr).getTime() / 1000));
			 }
			 if(!Strings.isBlank(subject3_pass_timeStr)){
				 student.setSubject3_pass_time((int) (sdf.parse(subject3_pass_timeStr).getTime() / 1000));
			 }
			 if(!Strings.isBlank(subject4_pass_timeStr)){
				 student.setSubject4_pass_time((int) (sdf.parse(subject4_pass_timeStr).getTime() / 1000));
			 }
			studentService.updateIgnoreNull(student);
			return Result.success("修改成功");
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return Result.error("修改失败");
		}
	}
	

	/**
	 * 体检录入
	 */
	@At("/toOne")
	@Ok("beetl:/platform/student/one/index.html")
	public void toOne(){
		
	}
	/**
	 * 加载数据
	 * @param name
	 * @param length
	 * @param start
	 * @param draw
	 * @param order
	 * @param columns
	 * @return
	 */
	@At
	@Ok("json:full")
	@RequiresAuthentication
	@RequiresPermissions("student.g.one")
	public Object toOneData(@Param("name") String name,@Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns) {
		Cnd cnd = Cnd.NEW();
		if (!Strings.isBlank(name)){
			cnd.and("name", "like", "%" + name + "%");
		}
		cnd.and("state", "=", 0);
		cnd.and("progress","=",0);
		cnd.and("enroll_state","=",1);
		cnd.and("enroll_progress","=",2);
		return studentService.data(length, start, draw, order, columns, cnd, null);
	}
	/**
	 * 修改
	 * @param id
	 * @return
	 */
	@At("/toOneEdit/?")
	@Ok("beetl:/platform/student/one/edit.html")
	@RequiresAuthentication
	@RequiresPermissions("student.g.one")
	public Object toOneEdit(String id) {
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("student", studentService.fetch(id));
		//档案归属主体
		map.put("company",companyService.fetch(studentService.fetch(id).getCompany_id()));
		//驾校
		map.put("schoolList",schoolService.find());
		return map;
	}
	/**
	 * 体检录入
	 * ---1.分配驾校
	 * ---2.分配驾考类型
	 * ---3.修改入学进度enroll_progerss（第3步，预约上门）
	 * @param ud_coach
	 * @param req
	 * @return
	 */
	@At
	@Ok("json")
	@RequiresAuthentication
	@RequiresPermissions("student.g.one")
	public Object toOneEditDo(@Param("..") Ud_student student) {
		try {
			//修改入学进入enroll_progress到第3步--预约上门
			student.setEnroll_progress(3);
			studentService.updateIgnoreNull(student);
			return Result.success("修改成功");
		} catch (Exception e) {
			return Result.error("修改失败");
		}
	}
	
	/**
	 * 入学录入（驾校端）
	 */
	@At("/toTwo")
	@Ok("beetl:/platform/student/two/index.html")
	@RequiresPermissions("student.g.two")
	public void toTwo(){
		
	}
	/**
	 * 加载数据
	 * @param name
	 * @param length
	 * @param start
	 * @param draw
	 * @param order
	 * @param columns
	 * @return
	 */
	@At
	@Ok("json:full")
	@RequiresAuthentication
	@RequiresPermissions("student.g.two")
	public Object toTwoData(@Param("name") String name,@Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns) {
		
		//获取当前用户
		Subject subject = SecurityUtils.getSubject();
        Sys_user user = (Sys_user) subject.getPrincipal();
        //获取所属主体
        String company_id=user.getUnit().getCompany_id();
        //获取所属主体下的驾校
        Cnd sCnd = Cnd.NEW();
       // sCnd.and("company_id", "=", company_id);
        sCnd.and("state", "=", 0);
        sCnd.and("delFlag", "=", 0);
        List<Ud_school> schools=schoolService.query(sCnd);
        List<String> schoolIds=new ArrayList<String>();
        if(schools !=null){
        	for(Ud_school s :schools){
        		schoolIds.add(s.getId());
        	}
        }
        //条件判断
		Cnd cnd = Cnd.NEW();
		if (!Strings.isBlank(name)){
			cnd.and("name", "like", "%" + name + "%");
		}
		cnd.and("state", "=", 0);
		cnd.and("progress","=",0);
		cnd.and("enroll_state","=",1);
		cnd.and("enroll_progress","=",3);
		cnd.and("school_id","IN",schoolIds);
		return studentService.data(length, start, draw, order, columns, cnd, null);
	}
	/**
	 * 修改
	 * @param id
	 * @return
	 */
	@At("/toTwoEdit/?")
	@Ok("beetl:/platform/student/two/edit.html")
	@RequiresAuthentication
	@RequiresPermissions("student.g.two")
	public Object toTwoEdit(String id) {
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("student", studentService.fetch(id));
		//获取驾校
		map.put("school", schoolService.fetch(studentService.fetch(id).getSchool_id()));
		//档案归属主体
		map.put("company",companyService.fetch(studentService.fetch(id).getCompany_id()));
		return map;
	}
	/**
	 * 入学录入
	 * ---1.修改基本信息
	 * ---2.判断是否体检通过
	 * ---3.体检通过 --修改入学进度enroll_progerss（第5步，预约上门）,学习进度progress（1，理论考试）
	 * @param ud_coach
	 * @param req
	 * @return
	 */
	@At
	@Ok("json")
	@RequiresAuthentication
	@RequiresPermissions("student.g.two")
	public Object toTwoEditDo(@Param("..") Ud_student student,HttpServletRequest request, @Param("::ht") String[] hts, @Param("::url") String[] urls) {
		try {
			//判断体检是否合格
			if(student.getPhysical_results() !=null && student.getPhysical_results()==1){
				//体检通过,修改状态
				student.setEnroll_progress(5);
				student.setProgress(1);
				//保存附件
				if (null != urls) {
					List<Ud_student_attachment> attachments = new ArrayList<Ud_student_attachment>();
					Map<String, Object> map = ImageUtils.UploadImgFileBase64(urls, 400, request);
					if ((boolean) map.get("status")) {
						List<String> urlList = (List) map.get("url");
						for (int i = 0; i < urlList.size(); i++) {
							Ud_student_attachment attachment = new Ud_student_attachment();
							attachment.setAttachment_type("ID_NO");
							attachment.setAttachment_url(urlList.get(i));
							attachment.setStudent_id(student.getId());
							attachments.add(attachment);
						}
					}
					attachmentService.add(attachments);
				}
				if (null != hts) {
					List<Ud_student_attachment> attachments = new ArrayList<Ud_student_attachment>();
					Map<String, Object> map = ImageUtils.UploadImgFileBase64(hts, 400, request);
					if ((boolean) map.get("status")) {
						List<String> urlList = (List) map.get("url");
						for (int i = 0; i < urlList.size(); i++) {
							Ud_student_attachment attachment = new Ud_student_attachment();
							attachment.setAttachment_type("CONTRACT");
							attachment.setAttachment_url(urlList.get(i));
							attachment.setStudent_id(student.getId());
							attachments.add(attachment);
						}
					}
					attachmentService.add(attachments);
				}
			}
			studentService.updateIgnoreNull(student);
			return Result.success("修改成功");
		} catch (Exception e) {
			return Result.error("修改失败");
		}
	}
	
	/**
	 * 科目一
	 */
	@At("/toSubjectOne")
	@Ok("beetl:/platform/student/subject/one/index.html")
	@RequiresPermissions("student.g.subject1")
	public void toSubjectOne(){
		
	}
	/**
	 * 加载数据
	 * @param name
	 * @param length
	 * @param start
	 * @param draw
	 * @param order
	 * @param columns
	 * @return
	 */
	@At
	@Ok("json:full")
	@RequiresAuthentication
	@RequiresPermissions("student.g.subject1")
	public Object toSubjectOneData(@Param("name") String name,@Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns) {
        //条件判断
		Cnd cnd = Cnd.NEW();
		if (!Strings.isBlank(name)){
			cnd.and("name", "like", "%" + name + "%");
		}
		cnd.and("state", "=", 0);
		cnd.and("progress","=",1);
		return studentService.data(length, start, draw, order, columns, cnd, null);
	}
	/**
	 * 修改
	 * @param id
	 * @return
	 */
	@At("/toSubjectOneEdit/?")
	@Ok("beetl:/platform/student/subject/one/edit.html")
	@RequiresAuthentication
	@RequiresPermissions("student.g.subject1")
	public Object toSubjectOneEdit(String id) {
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("student", studentService.fetch(id));
		//获取驾校
		map.put("school", schoolService.fetch(studentService.fetch(id).getSchool_id()));
		//档案归属主体
		map.put("company",companyService.fetch(studentService.fetch(id).getCompany_id()));
		return map;
	}
	/**
	 * 科目一
	 * ---1.判断是否通过
	 * ---2.记录分数
	 * ---3.通过，修改学习进度progress（2，操作培训）
	 * @param ud_coach
	 * @param req
	 * @return
	 */
	@At
	@Ok("json")
	@RequiresAuthentication
	@RequiresPermissions("student.g.subject1")
	public Object toSubjectOneEditDo(@Param("id") String id,@Param("subject1_is_pass") Integer subject1_is_pass,@Param("score") String score) {
		try {
			Ud_student student=studentService.fetch(id);
			if(null != subject1_is_pass && subject1_is_pass==1){
				student.setProgress(2);
				studentService.updateIgnoreNull(student);
			}
			//记录分数
			Ud_student_score score2=new Ud_student_score();
			score2.setIs_pass(subject1_is_pass);
			score2.setScore(score);
			score2.setStudent_id(id);
			score2.setSubject_type("subject1");
			Subject subject = SecurityUtils.getSubject();
	        Sys_user user = (Sys_user) subject.getPrincipal();
	        score2.setCreateby(user.getId());
	        score2.setCreateat((int)(System.currentTimeMillis()/1000));
			
	        scoreService.insert(score2);
			return Result.success("修改成功");
		} catch (Exception e) {
			return Result.error("修改失败");
		}
	}
	
	/**
	 * 操作培训--包干--科目二 
	 */
	@At("/toSubjectTwo")
	@Ok("beetl:/platform/student/subject/two/index.html")
	@RequiresPermissions("student.g.subject2")
	public void toSubjectTwo(){
		
	}
	/**
	 * 加载数据
	 * @param name
	 * @param length
	 * @param start
	 * @param draw
	 * @param order
	 * @param columns
	 * @return
	 */
	@At
	@Ok("json:full")
	@RequiresAuthentication
	@RequiresPermissions("student.g.subject2")
	public Object toSubjectTwoData(@Param("name") String name,@Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns) {
        //条件判断
		Cnd cnd = Cnd.NEW();
		if (!Strings.isBlank(name)){
			cnd.and("name", "like", "%" + name + "%");
		}
		cnd.and("state", "=", 0);
		cnd.and("progress","=",2);
		cnd.and("subject2_state","=",0);
		//培训模式为包干
		cnd.and("subject2_mode","=",1);
		return studentService.data(length, start, draw, order, columns, cnd, null);
	}
	/**
	 * 修改
	 * @param id
	 * @return
	 */
	@At("/toSubjectTwoEdit/?")
	@Ok("beetl:/platform/student/subject/two/edit.html")
	@RequiresAuthentication
	@RequiresPermissions("student.g.subject2")
	public Object toSubjectTwoEdit(String id) {
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("student", studentService.fetch(id));
		//获取驾校
		map.put("school", schoolService.fetch(studentService.fetch(id).getSchool_id()));
		//档案归属主体
		map.put("company",companyService.fetch(studentService.fetch(id).getCompany_id()));
		//场地
		map.put("fieldList", studentService.getFieldList());
		//教练
		map.put("coachList", studentService.getCoachList());
		return map;
	}
	/**
	 * 科目二（分配教练和场地）
	 * ---1.分配教练和场地
	 * ---2.subject2_state改为1培训中，subject2_progress改为4预约培训
	 * @param ud_coach
	 * @param req
	 * @return
	 */
	@At
	@Ok("json")
	@RequiresAuthentication
	@RequiresPermissions("student.g.subject2")
	public Object toSubjectTwoEditDo(@Param("id") String id,@Param("subject2_coach") String subject2_coach,@Param("subject2_field") String subject2_field) {
		try {
			Ud_student student=studentService.fetch(id);
			student.setSubject2_state(1);
			student.setSubject2_progress(4);
			student.setSubject2_trainer(subject2_coach);
			student.setSubject2_field(subject2_field);
			studentService.updateIgnoreNull(student);
			return Result.success("修改成功");
		} catch (Exception e) {
			return Result.error("修改失败");
		}
	}
	
	
	/**
	 * 操作培训--包干--科目三 
	 */
	@At("/toSubjectThree")
	@Ok("beetl:/platform/student/subject/three/index.html")
	@RequiresPermissions("student.g.subject3")
	public void toSubjectThree(){
		
	}
	/**
	 * 加载数据
	 * @param name
	 * @param length
	 * @param start
	 * @param draw
	 * @param order
	 * @param columns
	 * @return
	 */
	@At
	@Ok("json:full")
	@RequiresAuthentication
	@RequiresPermissions("student.g.subject3")
	public Object toSubjectThreeData(@Param("name") String name,@Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns) {
        //条件判断
		Cnd cnd = Cnd.NEW();
		if (!Strings.isBlank(name)){
			cnd.and("name", "like", "%" + name + "%");
		}
		cnd.and("state", "=", 0);
		cnd.and("progress","=",2);
		cnd.and("subject3_state","=",0);
		//培训模式为包干
		cnd.and("subject3_mode","=",1);
		return studentService.data(length, start, draw, order, columns, cnd, null);
	}
	/**
	 * 修改
	 * @param id
	 * @return
	 */
	@At("/toSubjectThreeEdit/?")
	@Ok("beetl:/platform/student/subject/three/edit.html")
	@RequiresAuthentication
	@RequiresPermissions("student.g.subject3")
	public Object toSubjectThreeEdit(String id) {
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("student", studentService.fetch(id));
		//获取驾校
		map.put("school", schoolService.fetch(studentService.fetch(id).getSchool_id()));
		//档案归属主体
		map.put("company",companyService.fetch(studentService.fetch(id).getCompany_id()));
		//场地
		map.put("fieldList", studentService.getFieldList());
		//教练
		map.put("coachList", studentService.getCoachList());
		return map;
	}
	
	/**
	 * 增加追踪服务
	 * @param id
	 * @return
	 */
	@At("/recordAdd/?")
	@Ok("beetl:/platform/student/recordAdd.html")
	public Object recordAdd(String id){
		return studentService.fetch(id);
	}
	
	/**
	 * 新增
	 * @param company
	 * @param req
	 * @return
	 */
	@At
	@Ok("json")
	@RequiresAuthentication
	public Object recordAddDo(@Param("..") Ud_student_record student_record, @Param("createAtStr") String createAtStr,HttpServletRequest req) {
		try {
			//设置创建人
			Subject subject = SecurityUtils.getSubject();
            Sys_user user = (Sys_user) subject.getPrincipal();
            student_record.setCreateBy(user.getId());
            //设置创建时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			int createAt = (int) (sdf.parse(createAtStr).getTime() / 1000);
			student_record.setCreateAt(createAt);
			studentRecordService.insert(student_record);
	        return Result.success("保存成功");
	    } catch (Exception e) {
	    	return Result.error(e.getMessage());
	    }
	}
	
	
	
	/**
	 * 首页
	 */
	@At("/recordList/?")
	@Ok("beetl:/platform/student/recordList.html")
	@RequiresAuthentication
	public String recordList(String id) {
		return id;
	}
	@At
	@Ok("json:full")
	@RequiresAuthentication
	public Object recordData(@Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns) {
		Cnd cnd = Cnd.NEW();
		return studentRecordService.data(length, start, draw, order, columns, cnd, null);
	}
	
	
	
	
	/**
	 * 科目三（分配教练和场地）
	 * ---1.分配教练和场地
	 * ---2.subject3_state改为1培训中，subject3_progress改为4预约培训
	 * @param ud_coach
	 * @param req
	 * @return
	 */
	@At
	@Ok("json")
	@RequiresAuthentication
	@RequiresPermissions("student.g.subject3")
	public Object toSubjectThreeEditDo(@Param("id") String id,@Param("subject3_coach") String subject3_coach,@Param("subject3_field") String subject3_field) {
		try {
			Ud_student student=studentService.fetch(id);
			student.setSubject3_state(1);
			student.setSubject3_progress(4);
			student.setSubject3_trainer(subject3_coach);
			student.setSubject3_field(subject3_field);
			studentService.updateIgnoreNull(student);
			return Result.success("修改成功");
		} catch (Exception e) {
			return Result.error("修改失败");
		}
	}
	
	
	@At
	@Ok("json") 
	@RequiresAuthentication
	public Object getSchool(String id){
		if(!Strings.isBlank(id)){
			return schoolService.fetch(id).getName();
		}else{
			return "";
		}
	}
	@At
	@Ok("json") 
	@RequiresAuthentication
	public Object getCompany(String id){
		if(!Strings.isBlank(id)){
			return companyService.fetch(id).getName();
		}else{
			return "";
		}
	}
	
}
